package com.lysj.admin.auth.management.feignImpl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lysj.admin.auth.management.AuthConstant;
import com.lysj.admin.auth.management.domain.Permission;
import com.lysj.admin.auth.management.service.PermissionService;
import com.lysj.admin.auth.utils.MailService;
import com.lysj.admin.common.auth.feign.AuthServiceFeign;
import com.lysj.admin.utils.web.HttpUtil;
import com.lysj.admin.utils.web.ParamUtil;
import com.lysj.admin.utils.web.Resp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author Created by zk on 2019-01-02 15:29
 * @description
 */
@RestController
@Slf4j
public class AuthServiceFeignImpl implements AuthServiceFeign {
    @Resource
    private PermissionService permissionService;
    @Value("${secret.key}")
    private String key;
    @Value("${secret.tokenExpiration}")
    private int tokenExpiration;
    @Value("${secret.tokenRefresh}")
    private int tokenRefresh;
    @Resource
    private MailService mailService;

    //-------------发送短信配置-----------------------------
    @Value("${sms.urlSendSms}")
    private String urlSendSms;  // 发送短信地址

    @Value("${sms.custCode}")
    private String custCode;   // 用户账号，必填

    @Value("${sms.custPwd}")
    private String custPwd;  // 用户密码，必填

    @Value("${sms.uid}")
    private String uid;  // 业务标识，选填，由客户自行填写不超过20位的数字

    @Value("${sms.spCode}")
    private String spCode;   // 长号码，选填

    @Value("${sms.needReport}")
    private String needReport;  // 是否需要状态报告


    @Override
    public Resp authentication(String token, String path) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC512(key)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return new Resp().error(Resp.Status.TOKEN_ERROR, "token异常,请重新登录");
        }
        String iss = jwt.getIssuer();
        String userId = jwt.getSubject();
        if (ParamUtil.isBlank(userId) || ParamUtil.isBlank(iss) || !AuthConstant.AUTH_NAME.equals(iss)) {
            return new Resp().error(Resp.Status.TOKEN_ERROR, "token异常,请重新登录");
        }
        //获取用户权限树
        List<Permission> permissions = permissionService.findByUserIdAndType(userId);
        if (ParamUtil.isBlank(permissions)) {
            return new Resp().error(Resp.Status.NO_ACCESS, "您尚未拥有该权限");
        }
        //匹配路径是否符合用户权限
        boolean isAccess = false;
        for (Permission permission : permissions) {
            if (permission.getPath().equals(path)) {
                isAccess = true;
                break;
            }
        }
        if (!isAccess) {
            return new Resp().error(Resp.Status.NO_ACCESS, "您尚未拥有该权限");
        }
        //判断用户token是否需要刷新
        Date expires = jwt.getExpiresAt();
        Date now = new Date();
        if ((now.getTime() - expires.getTime()) < tokenRefresh * 60 * 1000) {
            token = JWT.create().withIssuer(AuthConstant.AUTH_NAME).withSubject(userId)
                    .withExpiresAt(new Date(now.getTime() + tokenExpiration * 60 * 1000))
                    .sign(Algorithm.HMAC512(key));
        }
        return new Resp().success(token, null);
    }

    @Override
    public boolean sendSms(String code, String phone) {
        String content = "【来亿单】您的验证码为：" + code + "，请在15分钟内填写";
        // 签名，签名内容根据 “短信内容+客户密码”进行MD5编码后获得
        String sign = content + custPwd;
        sign = ParamUtil.md5(sign);

        StringBuilder sb = new StringBuilder();
        sb.append("{\"cust_code\":\"").append(custCode).append("\",\"sp_code\":\"").append(spCode);
        sb.append("\",\"content\":\"").append(content).append("\",\"destMobiles\":\"").append(phone);
        sb.append("\",\"uid\":\"").append(uid).append("\",\"need_report\":\"").append(needReport);
        sb.append("\",\"sign\":\"").append(sign).append("\"}");
        System.out.println("post内容1" + sb.toString());
        String resp = HttpUtil.sendJsonPost(urlSendSms, sb.toString());
        if (ParamUtil.isBlank(resp)) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public boolean sendEmail(String text, String email, String title) {
        boolean flag = true;
        try {
            mailService.sendHtmlMail(email, title, text);
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }


}
